﻿#include "CCharSet.h"
#include<iostream>
#ifdef _WIN32
#include<Windows.h>
#include<stringapiset.h>
#endif // DEBUG

CCharSet::CCharSet()
{
}


CCharSet::~CCharSet()
{
}

#ifdef _WIN32
//ANSI转为Unicode编码
const std::wstring CCharSet::AnsiToUnciode(const std::string& str)
{
	unsigned long dwSize = MultiByteToWideChar(CP_ACP, 0, str.c_str(), strlen(str.c_str()), NULL, 0);

	wchar_t* wstr = new wchar_t[dwSize + 1];
	memset(wstr, 0, sizeof(wchar_t) * (dwSize + 1));
	MultiByteToWideChar(CP_ACP, 0, str.c_str(), strlen(str.c_str()), wstr, dwSize);
	std::wstring buf = wstr;
	delete[] wstr;
	return buf;
}

//Unicode转Ansi
const std::string CCharSet::UnicodeToAnsi(const std::wstring& wstr)
{
	unsigned long dwSize = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);

	char* str = new char[dwSize + 1];
	memset(str, 0, sizeof(char) * (dwSize + 1));

	WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, str, dwSize, NULL, NULL);
	std::string buf = str;
	delete[] str;
	return buf;
}

//UTF8转ANSI
const std::string CCharSet::Utf8ToAnsi(const std::string& utf8)
{
	//UTF8转为Unicode
	/*unsigned long dwSize = MultiByteToWideChar(CP_UTF8, NULL, utf8, strlen(utf8), NULL, 0);

	wchar_t* wstr = new wchar_t[dwSize + 1];
	memset(wstr, 0, sizeof(wchar_t)* (dwSize + 1));

	MultiByteToWideChar(CP_UTF8, NULL, utf8, strlen(utf8), wstr, dwSize);*/

	std::wstring wstr = Utf8ToUncode(utf8);

	//Unicode转为ANSI
	return UnicodeToAnsi(wstr);
}

//ANSI转UTF8
const std::string CCharSet::AnsiToUtf8(const std::string& str)
{
	//ANSI转Unicode
	std::wstring wstr = AnsiToUnciode(str);
	//Unicode转UTF8
    return  UnicodeToUtf8(wstr);
}

//UTF8转Uicode
const std::wstring CCharSet::Utf8ToUncode(const std::string& utf8)
{
	unsigned long dwSize = MultiByteToWideChar(CP_UTF8, NULL, utf8.c_str(), strlen(utf8.c_str()), NULL, 0);

	wchar_t* wstr = new wchar_t[dwSize + 1];
	memset(wstr, 0, sizeof(wchar_t) * (dwSize + 1));

	MultiByteToWideChar(CP_UTF8, NULL, utf8.c_str(), strlen(utf8.c_str()), wstr, dwSize);
	std::wstring buf = wstr;
	delete[] wstr;
	return buf;
}

//Unciode转UTF8
const std::string CCharSet::UnicodeToUtf8(const std::wstring& wstr)
{
	unsigned long dwSize = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);

	char* utf8 = new char[dwSize + 1];
	memset(utf8, 0, sizeof(char) * (dwSize + 1));

	WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, utf8, dwSize, NULL, NULL);
	std::string buf = utf8;
	delete[] utf8;
	return buf;
}
#endif